<template>
	<j-load v-if="loading"></j-load>
	<!-- 报警配置 -->
	<view v-else style="padding-top:30upx">
		<j-timeOut v-if="requestErr"></j-timeOut>
		<view v-else>
			<view class="card-menu cu-list menu">
				<view class="cu-item bg-white">
					<view class="content">
						<!-- 开关 -->
						<view class="title">{{$t('JLink.configs.switch')}}</view>
					</view>
					<view class="action">
<!--						<switch class='cyan ' @change="handlerAlarmEnable" :class="alarmEnable?'checked':''" :checked="alarmEnable?true:false" color="#FF0025"></switch>-->
                        <j-switch @change="handlerAlarmEnable" :is-show-icon="true" inactiveColor="#829aa4" :value="alarmEnable?true:false"></j-switch>
					</view>
				</view>
				<view v-if="alarmEnable" class="cu-item bg-white" >
					<view class="content">
						<!-- 工作时间段 -->
						<view class="title">{{$t('JLink.configs.workingTime')}}</view>
					</view>
					<view class="action">
<!--						<switch class='cyan ' @change="handlerTimeEnable" :class="timeEnable?'checked':''" :checked="timeEnable?true:false" color="#FF0025"></switch>-->
                        <j-switch @change="handlerTimeEnable" :is-show-icon="true" inactiveColor="#829aa4" :value="timeEnable?true:false"></j-switch>
					</view>
				</view>
				<view
                    v-if="timeEnable&&alarmEnable"
                    class="cu-item bg-white "
                    @tap="openTime(i)"
                    v-for="(item, i) in alarmList" :key="i"
                >
					<view class="content">
						<!-- 时间段 -->
						<j-cell v-if="alarmList.length == 1" :title="$t('JLink.configs.period')+(i+1)"
							:tips="`${item.startTime} - ${item.endTime}`">
						</j-cell>
                        <j-cell-slider v-else
                            :tips="`${item.startTime} - ${item.endTime}`"
                            @jfdelete="onClick(item,i)"
                            @change="swipeChange"
                        >
                            <view slot="title">{{$t('JLink.configs.period')}}{{i+1}}</view>
                        </j-cell-slider>
					</view>
				</view>
				<view v-if="alarmList.length < 5 && (timeEnable && alarmEnable)" class="text-center" style="">
					<button class="cu-btn  line-cyan margin-top" style="background-color: #fff;width: 100%"
						@click="handleAddTime"> {{$t('JLink.publicText.add')}} </button>
				</view>
			</view>
			<view v-if="alarmEnable && isShowAlarm" class="cu-card case">
				<view class="cu-item">
					<!-- 报警类型 -->
					<view class="text-sm padding-left padding-top-sm text-gray">{{$t('JLink.configs.alarmType')}}</view>
					<checkbox-group class="block jf-checkbox" @change="CheckboxChange">
						<view class="cu-form-group" v-for="(item,i) in ALARMTYPE" :key="i">
							<view class="title">{{item.lable}}</view>
							<checkbox class='round primary' :class="item.check?'checked':''" :checked="item.check?true:false" :value="item.value"></checkbox>
						</view>
					</checkbox-group>
				</view>
			</view>
			<!-- 时间选择 模态框 -->
            <time-pick ref="timePick" :start="alarmList[timeIndex].startTime" :end="alarmList[timeIndex].endTime" :title="$t('JLink.configs.selectTime')" @confirm="confirmTime"></time-pick>
			<!-- 错误码提示 -->
			<error-modal :modalName="modalName" :errCode="errCode" @hideModal="hideModal"></error-modal>
		</view>
	</view>
</template>

<script>
import timePicker from "../components/picker/range-picker/range-picker"
import timePick from "../components/modal/timePick.vue"
import errorModal from "../components/modal/error"
import {getDeviceToken, VoLTE_PhoneList,VoLTE_AlarmType } from '@/API/api.js'
export default {
	components: {
		errorModal,
		timePick,
	},
	data() {
		return {
			isShowAlarm: true,
	       	token:'',
			modalName:'',
            timeIndex:0,
			errCode:'',
			alarmEnable:true,//报警类型是否使能
			timeEnable:true,//时间段是否使能
			timeRang:{
				startTime:'08:00:00',
				endTime:'23:59:59'
			},//时间段
			alarmTypes:{},
			loading:true,//加载
			requestErr:true,//请求失败
			ALARMTYPE : [
				{lable:this.$t('JLink.alramType.PIRAlarm'),value:'PIRAlarm',check:false},//徘徊检测告警
				{lable:this.$t('JLink.alramType.HumanDetect'),value:'HumanDetect',check:false},//人形检测告警
				{lable:this.$t('JLink.alramType.FaceDetection'),value:'FaceDetection',check:false},//人脸检测告警
				// {lable:t('alramType.FaceRecognition'),value:'FaceRecognition',check:false},//人脸识别告警
				// {lable:t('alramType.AppEventHumanDetectAlarm'),value:'AppEventHumanDetectAlarm',check:false}//人形检测
			],
			alarmList: [],
            options: [{
                text: this.$t('publicText.delete'),
                style: {
                    backgroundColor: '#dd524d'
                }
            }],
			isClick: false,
			sDisabled: false,
			isShowTimePick:false,
            isDisabled: false,
		}
	},
    onLoad(e) {
		const {sn,type,alarmEnable} = e;
		this.urlParams = {
			sn,type
		}
		
		this.isShowAlarm = alarmEnable!='false'
		console.log('传值=====',e,this.isShowAlarm);
    },
    onShow() {
		const {sn,type} = this.urlParams;
		this.loading = true;
		this.requestErr = true;
		this.handleDeviceToken(sn,type,(res)=>{
            this.loading = false;
			this.requestErr = false;
			const {token,alarmEnable,timeRange,alarmTypes,timeRangeExt} = res;
			this.token = token;
			this.alarmTypes = alarmTypes;
			this.alarmEnable = alarmEnable;
			this.timeEnable = timeRange.enable;
            if(timeRangeExt){
                console.log('timeRangeExt 存在')
                this.alarmList = timeRangeExt.map(item => {
                    let data = item.split('|')
                    return {startTime: data[1],endTime:data[2]}
                })
            }
            this.$set(this.alarmList, 0, {
                startTime: timeRange.startTime ? timeRange.startTime : '08:00:00',
                endTime: timeRange.endTime ? timeRange.endTime : '23:59:59',
            })
		},(code)=>{
			this.loading = false;
			this.requestErr = true;
			if(code){
				this.modalName = 'errorMessage';
				this.errCode = `v-${code}`;
			}
		})
		this.handleBack();
	},
    methods: {
		// 获取设备token以及关联手机列表
		handleDeviceToken(deviceId,type,callback,callfinally){
			getDeviceToken({deviceId}).then(res=>{
				let token= res.token;
				VoLTE_PhoneList(type,token).then(mes=>{
					const {code,data} = mes;
					if(code===2000){
						const {alarmTypes} = data;
						// this.phoneInfo = data;
						data.token = token;
						if(alarmTypes){
							let alarmTypes_keys = Object.keys(alarmTypes);
							ALARMTYPE.value.forEach(j=>{
								alarmTypes_keys.forEach(z => {
									// 对应已选择哪些报警类型
									if(j.value===z){
										j.check = alarmTypes[z];
									}
								})
							})
						}
						callback(data)
					}else{
						callfinally(code)
					}
				}).catch(()=>{
					callfinally()
				})
			}).catch(()=>{
				callfinally()
			})
		},
		handleBack(){},
		// 选择事件
		CheckboxChange(e){
			let values = e.detail.value;
			let obj={};
			this.ALARMTYPE.forEach(t=>{
				t.check = false;
				values.forEach(z=>{
					if(z===t.value){
						t.check = true;
					}
				})
			})
			values.forEach(t=>{
				obj[t] = true;
			})
			this.alarmTypes = obj;
			this.handleSubmit()
		},
        onClick(obj, index) {
            let list = this.alarmList
            if(list.length > 1) {
                let data = []
                for(let i = 0;i< list.length;i++) {
                    if(i!==index) {
                        data.push(list[i])
                    }
                }
                this.alarmList = data
                this.handleSubmit()
                this.isClick = true
                setTimeout(() => {
                    this.isClick = false;
                    this.isDisabled = this.alarmList.length > 1 ? false : true;
                },100)
            }
        },
        swipeChange(e, index) {
            this.isClick = false
        },
		// 提交
		handleSubmit(){
			uni.hideToast();
            this.timeIndex = 0 // 置为0，不然删除后html会报错
			const {type} = this.urlParams;
			const {alarmEnable,timeEnable,alarmTypes} = this;
			const {startTime,endTime} = this.alarmList[0];
			let Enable = alarmEnable ? timeEnable : false;//根据开关判断时间段是否使能
			let params = {
				alarmEnable,
				timeRange:{
					enable: Enable,
					startTime : alarmEnable && Enable ? startTime : '',
					endTime: alarmEnable && Enable ? endTime : ''
				},
                timeRangeExt: this.alarmList.map(item => `1|${item.startTime}|${item.endTime}`),
				alarmTypes: alarmEnable ? alarmTypes : {} ,
			}
			VoLTE_AlarmType(type,this.token,params).then(res=>{
				const {code,msg} = res;
				if(code!=2000){
					this.modalName = 'errorMessage';
					this.errCode = `v-${code}`
				}else{
					uni.showToast({
						title: this.$t('JLink.publicText.setSuccess'),//设置成功
					});
				}
			}).catch(()=>{})
		},
		// 报警类型是否使能
		handlerAlarmEnable  (e){
			this.alarmEnable = e;
			this.handleSubmit();
		},
		// 时间段是否使能
		handlerTimeEnable  (e){
			this.timeEnable = e;
			this.handleSubmit()
		},
		// 时间段模态框弹出
		openTime (index){
			console.log('打开时间弹窗===',this);
			// const timePick = uni.createSelectorQuery().in(this).select("#timePick")._component.$children
			// console.log('timePick===',timePick);
			// // this.isShowTimePick = true
			// this.$refs.timePick.open();
            console.log(index, 'index')
            this.timeIndex = index
            this.$refs.timePick.open()
		},
		hideModal(){
			this.modalName=''
		},
		// 时间段选择
		confirmTime (e){
			const{start,end} = e;
            this.$set(this.alarmList, this.timeIndex, {startTime:`${start.hour}:${start.min}:${start.second}`, endTime:`${end.hour}:${end.min}:${end.second}`})
			this.handleSubmit()
		},
		handleAddTime(){
			if(this.alarmList.length > 5 || this.isClick) return
			this.alarmList.push({
				startTime: '08:00:00',
				endTime: '23:59:59'
			})
			this.isDisabled = this.alarmList.length > 1 ? false : true;
			this.handleSubmit()
		}
    }
}
</script>

<style lang="less" scoped>
	@import '@/common/style/main.css';
    /deep/ .cell-headline {
        padding: 0;
        min-height: 0;
    }
    /deep/ .cell-title {
        font-size: 24rpx;
    }
</style>
